﻿/// <reference path="../utilities/Xpcom.js" />
///--------------------------------------------------------------------
/// <file name="Route.js">
///   Encapsulates a URI pattern and a request handler so that the
///   RoutingHandler can make decisions on where certain
///   HTTP requests should go.
/// </file>
///--------------------------------------------------------------------

NAMFox.ns(function() { with (NAMFox) {

this.Route = function(uriPattern, requestHandler) {
    /// <summary>
    ///   Creates a new instance of the Route class.
    /// </summary>
    /// <param name="uriPattern" type="String">
    ///   The URI pattern that this Route matches.
    /// </param>
    /// <param name="requestHandler" type="String">
    ///   The RequestHandler utilized when requests come
    ///   in that match the uriPattern.
    /// </param>
    
    this._uriPattern = uriPattern;
    this._requestHandler = requestHandler;
};

Route.prototype = {
    _requestHandler: null,
    _uriPattern: null,

    getPriority: function() {
        /// <summary>
        /// Gets the relative priority of this route.
        /// </summary>
        /// <returns type="Number" />

        return this._requestHandler.priority;
    },
    
    getRouteData: function(requestPath) {
        /// <summary>
        ///   Gets route data for the specific requestPath if and only if
        ///   there is a match between the request path and the route.
        /// </summary>
        /// <param name="requestPath" type="String">
        ///   The path of the URI for which the request was made.
        /// </param>
        /// <returns type="Object" />
        
        var groupNames = [];
        
        var rawPattern = this._uriPattern.replace(
            /\(\?<(.*?)>(.*?[^\\])\)/g,
            function (all, groupName, groupContent) {
                groupNames.push(groupName);
                return "(" + groupContent + ")";
            }
        );
        
        var matches = requestPath.match(new RegExp(rawPattern));
        
        if (matches) {
            var routeData = {};
            
            for (var i = 1; i < matches.length; ++i) {
                var match = matches[i];
                
                if (match) {
                    routeData[groupNames[i - 1]] = match;
                }
            }
            
            return {
                requestHandler: this._requestHandler,
                values: routeData
            };
        }
        
        return null;
    }
};

}});